<?php
/**
 * order php class
 * @author konakona
 * @date 2009-9-29
 * @version 1.0.1
 * 提供发送邮件、提交订单后台数据、处理作用
 */
class order{
    /**
     * 支付地址
     *
     * @var string
     */
    private $subject = "Your Link.";
    /**
     * 感谢您,已经成功支付
     *
     * @var string
     */
    private $subject2 = "Thank you!";
    /**
     * 支付链接信件内容
     *
     * @var mxied
     */
    private $content = "Dear client: \n\t";
    /**
     * 成功支付后的感谢信
     *
     * @var mxied
     */
    private $content2 = "Thank you!";
    /**
     * 发信箱
     *
     * @var string
     */
    private $formmail = 'konakona@great-panda.net';
    /**
     * 插入tour订单数据库
     *
     * @param array $_post
     */
	 public static function insertTourOrder($_post){
		
	 }
	 public static function insertCruiseOrder(){
		
	 }
	 /**
     * 将数据存储到session中
     * @param string $str
     */
	 public static function saveSession($name,$str){
		if(isset($_SESSION[$name])) session_unregister($$name);
		$_SESSION[$name] = $str;
	 }
	 /**
     * 检查游轮订单提交第一步的处理情况
     * @param string $_post
     */
	 public static function checkSteps1($_post){
		if($_post['shipname']==$_SESSION['shipname']) session_destroy();
		if($_post['shipname']=='') k::message("Do not be submitted from outside");
		foreach($_post as $key=>$value){
			if($value=='' ||$value==null)	k::message("Do not be submitted from outside",'javascript:history.go(-1);');
			$_post[$key] = k::striptags($value);
			$_post[$key] = k::escapeSQL($value);
		}
		$tmp = explode(",",$_post['city']);
		$tmp_date = explode("-",$_post['startdate']);
		$way = strtolower($tmp[1]);
		$weeknum = cruise::WeekTonum($tmp[2]);
		$price = flight::getPrice($_post['fid'],$tmp_date['1'],$way);
		if($_post['price']!=$price){
			k::message('price is error.','javascript:history.go(-1);');
		}

		//将数据存储到session中
		self::saveSession('shipname',$_post['shipname']);
		self::saveSession('city',$_post['city']);
		self::saveSession('price',$_post['price']);
		self::saveSession('realname',$_post['realname']);
		self::saveSession('nationality',$_post['nationality']);
		self::saveSession('phone',$_post['phone']);
		self::saveSession('email',$_post['email']);
		self::saveSession('id',$_post['fid']);
		self::saveSession('startdate',$_post['startdate']);
	}
	/**
	* 创建邮轮订单
	*/
	 public static function create_cruise_order(){
		$tmp_city = explode(",",$_SESSION['city']);
		$weeknum = cruise::WeekTonum($tmp_city[2]);
		$tmp_city = explode(">>",$tmp_city[0]);
		$time = time();
		$select_sql = "select cid from cruise,cruise_city where cruise.city_id = cruise_city.city_id and cruise.city_id =(select city_id from cruise_city where  Begin_city='{$tmp_city[0]}' and End_city = '{$tmp_city[1]}')";
		$tmp_result = mysql::connect()->fetch_all($select_sql);
		$cid = $tmp_result[0]['cid'];//邮轮的id
		$url = array();
		$url['cid'] = $cid;
		$url['time'] = $time;
		$url['uniqid'] = uniqid('konakona');//赋予变量前缀
		$hmac = self::getHmacValue(array('cid','time', 'uniqid'));
		$url['hmac'] = strtoupper($hmac);
		//插入数据库
		$insert_sql = "INSERT INTO cruise_order values('','{$cid}','{$_SESSION[realname]}','{$_SESSION[nationality]}','{$_SESSION[phone]}','{$_SESSION[email]}','{$_SESSION[startdate]}','{$_SESSION[price]}','{$url[uniqid]}','{$time}','".k::getip()."',0,0,0,0,0)";
		mysql::connect()->query($insert_sql);
		//发送24小时有效支付地址给客户的邮箱
		/* //发送给网站方的信
		$title = 'You have new Order from Chinatrvelguide!';
		$body = "<span style='color:gray'><a href='mailto:{$_SESSION[email]}'>{$_SESSION[realname]}</a></span> at <span style='color:gray'>".date("Y-m-d h:i:s",$time)."</span> creat an cruise order,please click this link to read<a href='../admin.php'>";
		$body .="\r \t <span style='color:red'><b>You can reply this e-mail to the client!</b></span>";
		*/
		header('Content-Type: text/html; charset=gb2312');
		$client_title = "thank you for booking the cruise,please pay that money";
		$client_body = "pay money<a href='http://localhost/beijing/index.php?c=pay&t=c&key={$url['hmac']}'>Link</a>";
		k::import('plugin.mail');
		if(!mail::run($client_title,$client_body,$_SESSION['email'],'contact@chinatravelguide.com.cn','chinatravelguide')){
			session_destroy();
			k::message("邮箱服务器长时间没有响应，邮件发送失败，订单已生成，请联系官方人员或通过以下连接支付 <a href='http://localhost/beijing/index.php?c=pay&t=c&key={$url['hmac']}'>Link</a>其实正式情况下-，- 这段话你是不可能看到的……");
		} else {
			session_destroy();
			k::message('Your order has been successfully, please be patient reply',"index.php?c=pay&t=c&key={$url['hmac']}");
		}
		echo "邮箱服务器长时间没有响应，邮件发送失败，订单已生成，请联系官方人员或通过以下连接支付 <a href='http://localhost/beijing/index.php?c=pay&t=c&key={$url['hmac']}'>Link</a>其实正式情况下-，- 这段话你是不可能看到的……";
	}
	// $url = http_build_query($url);
	/**
	* 创建邮轮订单
	*/
	public static function create_tour_order($_post){
        $_post = k::striptags($_post);
        if(!is_numeric($_post['id'])){
            k::message('Code is bad','javascript:history.go(-1);');
        }
        foreach($_post as $k=>$v){
			echo $v;exit;
			//k::message('nationality is error','javascript:history.go(-1);');
		}
        if($_post['hotel_requirements']=='Select'){
            $_post['hotel_requirements']=0;
        }
        if($_post['number_rooms']=='Select'){
            $_post['number_rooms']=0;
        }
        foreach($_post as $key=>$value){
            $_post[$key] = k::escapeSQL($value);
        }
        //增加salt检测，如果已存在，重新创建后插入再数据库
       $api = substr(uniqid(rand()), -6);
       $sql = "INSERT INTO `order` (`oid` ,`tid`,`realname` ,`nationality` ,`phone` ,`email` ,`people_party` ,`hotel_requirements` ,`number_rooms` ,`transportation_information` ,`start_date` , `end_date` ,`addtime` ,`ip` ,`payment_state` ,`revision_state` ,`remarks`,`payment_api`)VALUES (NULL , '{$_post[tourcode]}', '{$_post[realname]}', '{$_post[nationality]}', '{$_post[phone]}', '{$_post[email]}', '{$_post[people_party]}', '{$_post[hotel_requirements]}', '{$_post[number_rooms]}', '{$_post[transportation_information]}', '{$_post[start_date]}', '{$_post[end_date]}','".time()."', '{$_post[ip]}', '0', '0', '{$_post[remarks]}','{$api}');";
        mysql::connect()->query($sql);

        //Send To client
        //self::sendmail('$_post[email]',2,2);
        //Send To Yuntong
        $url = self::sendmail("k::$config[WEB_ADMIN_EMAIL]",1,1,$_post['tourcode'],$api);
        k::message('Order OK',$url);
        //Sorry! Your name and the email address are required. 
    }
	/**
     * 生成加密URL标签
     *
     * @pparams
     * @param int $outputCharset 网页编码
     * @param string $secureKey 支付序列号
     */
	public static function getHmacValue($params = array(), $outputCharset = 'UTF-8', $secureKey = 'konakona'){
		$str = array();
		if(!is_array($params)) return FALSE;
		//从cruise_order 提取 cid addtime uniquid
		foreach ($params as $key){
			if(array_key_exists($key, $_REQUEST)){
				$value = urldecode($_REQUEST[$key]);
				$__charset = mb_detect_encoding($value);
				if($__charset != $outputCharset){
					@$str[$key] .= mb_convert_encoding($value, $outputCharset, "GBK, GB2312, UTF-8");
				}else{
					@$str[$key] .= $value;
				}
			}
		}
		$str = urldecode(http_build_query($str));

		$key = &$secureKey;// 自定义密钥
		$b = 3400;
		if (strlen($key) > $b) $key = pack("H*",md5($key));
		$key = str_pad($key, $b, chr(0x00));
		$ipad = str_pad('', $b, chr(0x36));
		$opad = str_pad('', $b, chr(0x5c));
		$k_ipad = $key ^ $ipad ;
		$k_opad = $key ^ $opad;
		return md5($k_opad . pack("H*",md5($k_ipad . $str)));
	}
	/**
     * 对比标签
     *
     * @param array $pparams 参数
     * @param int $outputCharset 网页编码
     * @param string $secureKey 支付序列号
     */
	public static function VSHmacValue($params = array(), $outputCharset = 'UTF-8', $secureKey = 'konakona'){
		$_REQUEST = array_merge($_GET,$_POST);
		$str = array();
		if(!is_array($params)) return FALSE;
		
		//从数据库提取api，进行对比。
		//提取:cid
		foreach ($params as $key){
		if(array_key_exists($key, $_REQUEST))
		{
		$value = _urldecode($_REQUEST[$key]);
		$__charset = mb_detect_encoding($value);
		if($__charset != strtoupper($outputCharset))
		{
		@$str[$key] .= mb_convert_encoding($value, $outputCharset, "GBK, GB2312, UTF-8");
		}
		else
		{
		@$str[$key] .= $value;
		}
		}
		}
		$str = urldecode(http_build_query($str));

		$key = &$secureKey;// 自定义密钥
		$b = 3400;
		if (strlen($key) > $b) $key = pack("H*",md5($key));
		$key = str_pad($key, $b, chr(0x00));
		$ipad = str_pad('', $b, chr(0x36));
		$opad = str_pad('', $b, chr(0x5c));
		$k_ipad = $key ^ $ipad ;
		$k_opad = $key ^ $opad;

		return md5($k_opad . pack("H*",md5($k_ipad . $str)));
		}
		/**
		 * 列出所有tour的订单
		 * @param int $pid 
		 */
		public static function order_list($tablename,$pid,$row=10){
			if($pid == 0) $pid = 1;

			if($pid == 1){
				$sql = "select * from {$tablename}_order limit ".($pid-1).",$row";
			}else{
				$page_start  = ($pid-1)+$row;
				$sql = "select * from {$tablename}_order limit ".($page_start-1).",$row";
			}
			return mysql::connect()->fetch_all($sql);
		}
		/**
		 * 客服处理状态
		 * @param <type> $id
		 * @param <type> $table
		 * @param <type> $status
		 * @param <type> $r 
		 */
		public static function chuli($id,$table,$status,$r){
			if(isset($_SESSION['kona_admin'])){
				$name = $_SESSION['kona_admin'];
			}else{
				$name = $_SESSION['OT_admin'];
			}
			mysql::connect()->query("UPDATE `cruise_order` SET `revision_state` = '{$status}',`remarks` = '{$r}',`ot_name`='{$name}' WHERE `co_id` =$id");
		}
}